<template>
  <div class="login-register">
    <!-- 登录或注册表单 -->
    <el-form
        ref="formRef"
        :model="formData"
        style="max-width: 400px; margin: 100px auto;"
        :rules="rules"
        label-width="80px"
        @keyup.enter="handleSubmit"
    >
      <h3>{{ isLogin ? '用户登录' : '用户注册' }}</h3>

      <!-- 账号 -->
      <el-form-item label="账号" prop="username">
        <el-input
            clearable
            v-model="formData.username"
            prefix-icon="User"
        ></el-input>
      </el-form-item>

      <!-- 密码 -->
      <el-form-item label="密码" prop="password">
        <el-input
            clearable
            v-model="formData.password"
            prefix-icon="Lock"
            type="password"
        ></el-input>
      </el-form-item>

      <!-- 注册时的确认密码 -->
      <el-form-item v-if="!isLogin" label="确认密码" prop="confirmPassword">
        <el-input
            clearable
            v-model="formData.confirmPassword"
            prefix-icon="Lock"
            type="password"
        ></el-input>
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item class="loginBtn">
        <el-button type="primary" size="small" @click="handleSubmit">
          {{ isLogin ? '登录' : '注册' }}
        </el-button>
        <el-link type="primary" size="small" @click="toggleMode">
          {{ isLogin ? '去注册' : '去登录' }}
        </el-link>
      </el-form-item>
    </el-form>

    <p>
      {{tok}}
      {{message1}}
    </p>
  </div>
</template>

<script setup>
import {ref, inject} from 'vue';
import {ElMessage} from 'element-plus';
import {useRouter} from 'vue-router';
// import  {to}
import axios from "axios";
import {getInfo, toLogin, toRegister} from "@/api/user.js";

const router = useRouter();
// const axios = inject('$axios')
// 表单引用
const formRef = ref(null);
// 当前模式：true 表示登录，false 表示注册
const isLogin = ref(true);

const  message1 =ref('')
const  tok =ref('')


// 表单数据
const formData = ref({
  username: 'admin',
  password: '1234',
  confirmPassword: ''
});

// 触发表单项的校验
const triggerValidation = (fieldName) => {
  if (formRef.value) {
    formRef.value.validateField(fieldName);
  }
};

// 表单校验规则
const rules = {
  username: [
    {required: true, message: '请输入账号', trigger: 'blur'},
    {min: 3, max: 15, message: '账号长度应在 3 到 15 个字符之间', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'},
    {min: 3, max: 20, message: '密码长度应在 3 到 20 个字符之间', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (!isLogin.value) {
          // 注册时校验确认密码
          if (formData.value.confirmPassword !== '' && value !== formData.value.confirmPassword) {
            callback(new Error('两次输入的密码不一致'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    {required: () => !isLogin.value, message: '请再次输入密码', trigger: 'blur'},
    {
      validator: (rule, value, callback) => {
        if (!isLogin.value) {
          if (value !== formData.value.password) {
            callback(new Error('两次输入的密码不一致'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 提交表单
const handleSubmit = () => {
  formRef.value.validate(async valid => {
    if (!valid) return;
    if (isLogin.value) {
      const loginBody ={
        username: formData.value.username,
        password: formData.value.password
      }
      // 登录逻辑
      const res = await toLogin(loginBody)
      if (res.code === 200)
      {
        localStorage.setItem('token', res.token);
         await getUserInfo()
        await router.push('/');
        return ElMessage.success(res.msg);
      }
    } else {
      // 注册逻辑
      const registerBody = {
        username: formData.value.username,
        password: formData.value.password,
        nickname: formData.value.username // 可根据需要让用户输入昵称
      }
      const res = await toRegister(registerBody)
      if (res.code === 200) {
        ElMessage.success('注册成功，请登录！')
        isLogin.value = true;
        resetForm();
      } else {
        ElMessage.error(res.msg || '注册失败')
      }
    }
  });
};


async function getUserInfo() {
  try {
    const res = await getInfo()
    if (res.code === 200) {
      localStorage.setItem("user", JSON.stringify(res.user))
      localStorage.setItem("userId", res.user.id)
    } else {
      ElMessage.error(res.msg || '获取用户信息失败')
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
  }
}

// 切换登录/注册模式
const toggleMode = () => {
  isLogin.value = !isLogin.value;
  resetForm();
};

// 重置表单
const resetForm = () => {
  formData.value = {
    username: '',
    password: '',
    confirmPassword: ''
  }
};
</script>

<style scoped>
.login-register {
  text-align: center;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fff;
}

.el-form {
  border: none;
  padding: 32px 36px 24px 36px;
  border-radius: 18px;
  box-shadow: 0 8px 32px rgba(80, 120, 255, 0.10), 0 1.5px 6px rgba(0,0,0,0.04);
  background: #fff;
  min-width: 340px;
  margin: 0 auto;
}

h3 {
  margin-bottom: 24px;
  font-weight: 700;
  color: #3b3b3b;
  letter-spacing: 1px;
}

.loginBtn {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.el-button[type="primary"] {
  box-shadow: 0 2px 8px rgba(80, 120, 255, 0.12);
  border-radius: 8px;
  font-weight: 600;
  letter-spacing: 1px;
  padding: 0 24px;
}

.el-link {
  margin-left: 20px;
  color: #5060ff;
  font-weight: 500;
  font-size: 15px;
}

.el-form-item {
  margin-bottom: 18px;
}

.el-input__wrapper {
  border-radius: 8px !important;
}

/* 响应式 */
@media (max-width: 600px) {
  .el-form {
    min-width: 90vw;
    padding: 18px 8vw 12px 8vw;
  }
}
</style>
